/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.command.phonenumber;

import apus.command.AbstractCommand;
import apus.entity.RealPhoneNumber;
import apus.entity.Subscriber;
import apus.exception.BusinessException;
import apus.persistence.AbstractDAO;
import apus.persistence.OrganizationDAO;
import apus.persistence.PersonDAO;
import apus.persistence.PhoneNumberDAO;
import apus.services.ServiceLocator;
import java.util.Arrays;
import java.util.List;

/**
 * The <code>AddPhoneNumberCommand</code> class represents command for adding 
 * new phone number to the database.
 * @author  Maxim Vasilevsky
 * @author  Roman Dyatkovsky
 * @since APUS v0.4
 * @see AbstractCommand
 */
public class AddPhoneNumberCommand <TypeEn extends Subscriber, TypeDAO extends AbstractDAO<TypeEn>> extends AbstractCommand {
    
    private Class<TypeDAO> clazz;
    private final static String NUMBER = "Phone number";
    private final static String OWNER_ID = "Owner";
    
    
    private final static String[] paramsNames = { NUMBER, OWNER_ID };
    
    public AddPhoneNumberCommand(Class<TypeDAO> clazz,String name) {
        super(name);
        this.clazz=clazz;
    }
    
    @Override
    public void execute() {
        
        String stringId = params.get(OWNER_ID);
        int ID;
        try {
            ID = Integer.parseInt(stringId);
        } catch(NumberFormatException e){
            throw new BusinessException("Wrong ID format: "+stringId, e);
        }
        AbstractDAO<TypeEn> DAO = ServiceLocator.getService(clazz);
        Subscriber subscriber = DAO.read(ID);
        
        if (subscriber==null){
            throw new BusinessException("RealSubscriber not found");
        }

        PhoneNumberDAO phoneNumberDAO = ServiceLocator.getService(PhoneNumberDAO.class);
        phoneNumberDAO.create(new RealPhoneNumber(subscriber,params.get(NUMBER))); 

    }
    
    
    @Override
    public List<String> getParamNames() {
        return Arrays.asList(paramsNames);
    }
    
    public static AddPhoneNumberCommand getAddPhoneNumberToPersonCommand(){
        return new AddPhoneNumberCommand(PersonDAO.class, "Add phone number to person");
    }
    
    public static AddPhoneNumberCommand getAddPhoneNumberToOrganizationCommand(){
        return new AddPhoneNumberCommand(OrganizationDAO.class, "Add phone number to organization");
    }
    
}
